'''
用户设置相关的API路由
'''
from flask import Blueprint, request, jsonify, g
from psycopg2.extras import RealDictCursor
from config.config import AI_PROVIDERS
from services.auth_service import login_required

# 创建蓝图
user_bp = Blueprint('user', __name__, url_prefix='/api')

# 1. 获取用户AI设置
@user_bp.route('/user/settings', methods=['GET'])
def get_user_settings():
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 获取请求中的用户名，默认为admin
    username = request.args.get('username', 'admin')
    
    cursor.execute('SELECT * FROM user_settings WHERE username = %s', (username,))
    settings = cursor.fetchone()
    
    if not settings:
        # 如果没有找到设置，返回默认设置
        return jsonify({
            'status': 'success',
            'data': {
                'username': username,
                'preferred_ai_provider': 'openai',
                'openai_api_key': '',
                'deepseek_api_key': '',
                'ai_providers': AI_PROVIDERS
            }
        })
    
    # 处理API密钥，不返回完整密钥
    openai_api_key = settings['openai_api_key'] or ''
    deepseek_api_key = settings['deepseek_api_key'] or ''
    
    # 如果有API密钥，只返回前几个字符和后几个字符
    if openai_api_key:
        openai_api_key = openai_api_key[:3] + '****' + openai_api_key[-4:]
    if deepseek_api_key:
        deepseek_api_key = deepseek_api_key[:3] + '****' + deepseek_api_key[-4:]
    
    return jsonify({
        'status': 'success',
        'data': {
            'username': settings['username'],
            'preferred_ai_provider': settings['preferred_ai_provider'],
            'openai_api_key': openai_api_key,
            'deepseek_api_key': deepseek_api_key,
            'ai_providers': AI_PROVIDERS
        }
    })

# 2. 更新用户AI设置
@user_bp.route('/user/settings', methods=['POST'])
def update_user_settings():
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    data = request.json
    if not data:
        return jsonify({
            'status': 'error',
            'message': '无效的请求数据'
        }), 400
    
    username = data.get('username', 'admin')
    preferred_ai_provider = data.get('preferred_ai_provider')
    openai_api_key = data.get('openai_api_key')
    deepseek_api_key = data.get('deepseek_api_key')
    
    # 验证AI提供商
    if preferred_ai_provider and preferred_ai_provider not in AI_PROVIDERS:
        return jsonify({
            'status': 'error',
            'message': f'不支持的AI提供商: {preferred_ai_provider}'
        }), 400
    
    try:
        # 检查用户是否已存在
        cursor.execute('SELECT * FROM user_settings WHERE username = %s', (username,))
        existing_user = cursor.fetchone()
        
        if existing_user:
            # 更新现有用户
            update_fields = []
            update_values = []
            
            if preferred_ai_provider:
                update_fields.append('preferred_ai_provider = %s')
                update_values.append(preferred_ai_provider)
            
            # 只有在提供了新API密钥且不是掩码时才更新
            if openai_api_key and '****' not in openai_api_key:
                update_fields.append('openai_api_key = %s')
                update_values.append(openai_api_key)
            
            if deepseek_api_key and '****' not in deepseek_api_key:
                update_fields.append('deepseek_api_key = %s')
                update_values.append(deepseek_api_key)
            
            if update_fields:
                update_fields.append('updated_at = NOW()')
                update_query = f'''
                UPDATE user_settings 
                SET {', '.join(update_fields)}
                WHERE username = %s
                RETURNING *
                '''
                cursor.execute(update_query, update_values + [username])
                updated_user = cursor.fetchone()
                conn.commit()
                
                return jsonify({
                    'status': 'success',
                    'message': '用户设置已更新',
                    'data': updated_user
                })
            else:
                return jsonify({
                    'status': 'success',
                    'message': '没有变更需要更新',
                    'data': existing_user
                })
        else:
            # 创建新用户
            cursor.execute('''
            INSERT INTO user_settings 
            (username, preferred_ai_provider, openai_api_key, deepseek_api_key)
            VALUES (%s, %s, %s, %s)
            RETURNING *
            ''', (
                username,
                preferred_ai_provider or 'openai',
                openai_api_key or None,
                deepseek_api_key or None
            ))
            new_user = cursor.fetchone()
            conn.commit()
            
            return jsonify({
                'status': 'success',
                'message': '用户设置已创建',
                'data': new_user
            })
    
    except Exception as e:
        conn.rollback()
        return jsonify({
            'status': 'error',
            'message': f'更新用户设置时出错: {str(e)}'
        }), 500

# 3. 验证API密钥
@user_bp.route('/user/validate-api-key', methods=['POST'])
def validate_api_key():
    data = request.json
    if not data:
        return jsonify({
            'status': 'error',
            'message': '无效的请求数据'
        }), 400
    
    provider = data.get('provider')
    api_key = data.get('api_key')
    
    if not provider or not api_key:
        return jsonify({
            'status': 'error',
            'message': '缺少必要参数'
        }), 400
    
    # 添加实际的API密钥验证逻辑
    if provider == 'deepseek':
        try:
            import requests
            from config.config import DEEPSEEK_API_BASE
            
            # 发送一个简单请求来验证API密钥
            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {api_key}"
            }
            
            data = {
                "model": "deepseek-chat",
                "messages": [
                    {"role": "user", "content": "Hello"}
                ],
                "max_tokens": 5  # 设置较小的值以节省资源
            }
            
            response = requests.post(
                f"{DEEPSEEK_API_BASE}/chat/completions", 
                headers=headers, 
                json=data,
                timeout=10  # 较短的超时以快速验证
            )
            
            response_json = response.json()
            
            # 检查响应是否包含错误
            if 'error' in response_json:
                return jsonify({
                    'status': 'error',
                    'message': f"API密钥验证失败: {response_json.get('error', {}).get('message', '未知错误')}",
                    'is_valid': False,
                    'details': response_json
                }), 400
            else:
                return jsonify({
                    'status': 'success',
                    'message': 'API密钥有效',
                    'is_valid': True
                })
                
        except Exception as e:
            return jsonify({
                'status': 'error',
                'message': f'验证过程出错: {str(e)}',
                'is_valid': False
            }), 500
    
    elif provider == 'openai':
        try:
            import openai
            from config.config import OPENAI_MODEL
            
            # 保存当前API密钥
            temp_api_key = openai.api_key
            openai.api_key = api_key
            
            # 发送一个简单请求来验证API密钥
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",  # 使用较小的模型以节省成本
                messages=[
                    {"role": "user", "content": "Hello"}
                ],
                max_tokens=5,  # 设置较小的值以节省资源
                timeout=10  # 较短的超时以快速验证
            )
            
            # 恢复之前的API密钥
            openai.api_key = temp_api_key
            
            return jsonify({
                'status': 'success',
                'message': 'API密钥有效',
                'is_valid': True
            })
            
        except Exception as e:
            # 恢复之前的API密钥
            openai.api_key = temp_api_key if 'temp_api_key' in locals() else None
            
            return jsonify({
                'status': 'error',
                'message': f'验证过程出错: {str(e)}',
                'is_valid': False
            }), 500
    
    else:
        return jsonify({
            'status': 'error',
            'message': f'不支持的AI提供商: {provider}',
            'is_valid': False
        }), 400

# 获取所有用户
@user_bp.route('/users', methods=['GET'])
@login_required
def get_users():
    print(f"[用户API] 用户 {g.current_user.get('username', '未知')} 请求获取用户列表")
    print(f"[用户API] 当前用户详情: {g.current_user}")
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 获取当前用户的租户ID
    tenant_id = g.current_user.get('tenant_id')
    print(f"[用户API] 当前用户租户ID: {tenant_id}")
    
    # 检查是否仅获取当前租户的用户
    tenant_only = request.args.get('tenant_only', 'true').lower() in ('true', '1', 'yes')
    print(f"[用户API] 是否仅获取当前租户用户: {tenant_only}")
    
    try:
        # 获取同一租户下的所有用户
        query = '''
        SELECT id, username, email, role, status, tenant_id, last_login, created_at, updated_at 
        FROM users 
        WHERE status = 'active' '''
        
        params = []
        
        # 如果只获取当前租户用户，添加租户过滤条件
        if tenant_only and tenant_id:
            query += " AND tenant_id = %s"
            params.append(tenant_id)
        
        query += " ORDER BY username"
        
        print(f"[用户API] 执行SQL: {query}")
        print(f"[用户API] 参数: {params}")
        
        cursor.execute(query, params)
        users = cursor.fetchall()
        print(f"[用户API] 找到 {len(users)} 个用户")
        
        # 格式化日期时间
        for user in users:
            if 'created_at' in user and user['created_at']:
                user['created_at'] = user['created_at'].isoformat()
            if 'updated_at' in user and user['updated_at']:
                user['updated_at'] = user['updated_at'].isoformat()
            if 'last_login' in user and user['last_login']:
                user['last_login'] = user['last_login'].isoformat()
        
        return jsonify({
            'status': 'success',
            'data': users
        })
    
    except Exception as e:
        print(f"[用户API错误] 获取用户列表失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'获取用户列表失败: {str(e)}'
        }), 500 